package com.hzncc.flowable_diboot.coderule.aspect;

import com.diboot.core.util.ContextHolder;
import com.hzncc.flowable_diboot.coderule.annotation.CodeRule;
import com.hzncc.flowable_diboot.coderule.service.CodeRuleService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.flowable.common.engine.impl.util.ReflectUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

@Aspect
@Component
public class CodeRuleAspect {

    @Pointcut("@annotation(com.hzncc.flowable_diboot.coderule.annotation.CodeRule)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        CodeRule annotation = method.getAnnotation(CodeRule.class);
        // 实体
        String entity = annotation.entity();
        // 规则编码
        String code = annotation.ruleCode();
        // 待填充字段
        String property = annotation.property();
        CodeRuleService service = ContextHolder.getBean(CodeRuleService.class);
        for (Object arg : args) {
            // 判断是否是目标实体
            if (arg.getClass().getName().equals(entity)) {
                Class<?> clz = arg.getClass();
                String simpleCode = service.generateCode(code);
                Field field = ReflectionUtils.findField(clz, property);
                if (field != null) {
                    Method setter = ReflectUtil.getSetter(property, clz, String.class);
                    setter.invoke(arg,simpleCode);
                }
            }
            if (arg.getClass().getName().equals("java.util.List")) {
                List list = (List) arg;
                Class<?> clz = list.get(0).getClass();
                if (clz.getName().equals(entity)) {
                    int size = list.size();
                    List<String> strings = service.generateCode(code, size);
                    Field field = ReflectionUtils.findField(clz, property);
                    for (int i = 0; i < list.size(); i++) {
                        if (field != null) {
                            Method setter = ReflectUtil.getSetter(property, clz, String.class);
                            setter.invoke(list.get(i),strings.get(i));
                        }
                    }
                }
            }
        }
        Object proceed = pjp.proceed(args);
        return proceed;
    }

}
